# ==============================================================================
# analysis-pretrends.R
# author: Anselm Hager / Bernhard Clemm
# ==============================================================================

dir <- dirname(dirname(rstudioapi::getSourceEditorContext()$path))
source(paste0(dir, "/code/setup-packages.R"))

# DATA =========================================================================

load(paste0(dir, "/data/data_processed.RData"))

# TWFE event study estimator ===================================================

## Event study function ####
run_twfe_event <- function(dat, controls = NULL) {
  twfe_event_results <- vector(mode = "list", length = 3)

  if (is.null(controls)) {
    form <- as.formula(
      "percent ~ i(time_to_treat_twfe, ref = c(-1,-10000)) | ags + election_date_int"
    )
  } else {
    form <- as.formula(
      paste("percent ~ i(time_to_treat_twfe, ref = c(-1,-10000)) + ",
        paste(controls, collapse = " + "),
        sep = ""
      ) %>%
        paste(., "| ags + election_date_int", sep = " ")
    )
  }

  for (i in 1:length(dat)) {
    party_results <- vector(mode = "list", length = 2)
    parties <- c("afd", "green")

    for (j in 1:length(party_results)) {
      twfe <- fixest::feols(form,
        data = dplyr::filter(dat[[i]], party == parties[j]),
        cluster = ~ags
      ) %>%
        broom::tidy(conf.int = TRUE) %>%
        dplyr::filter(grepl("time_to", term)) %>%
        dplyr::mutate(t = as.double(
          str_replace_all(term, c("time_to_treat_twfe::" = "", ":treated" = ""))
        )) %>%
        dplyr::select(t, estimate, conf.low, conf.high) %>%
        dplyr::bind_rows(tibble(
          t = -1, estimate = 0,
          conf.low = 0, conf.high = 0
        )) %>%
        mutate(
          method = "TWFE",
          party = parties[j]
        )

      party_results[[j]] <- twfe
    }

    twfe_event_results[[i]] <- dplyr::bind_rows(party_results)
  }

  names(twfe_event_results) <- names(dat)

  return(twfe_event_results)
}

twfe_event <- run_twfe_event(data_processed)
twfe_event_controls <- run_twfe_event(
  data_processed,
  controls = c("prop_agri", "prop_heathen", "prop_unempl")
)

## Plotting function ####
plotting_events <- function(dat, prty, title) {
  dat <- dat %>%
    filter(party == prty) %>%
    dplyr::mutate(
      estimate = estimate * 100,
      conf.low = conf.low * 100,
      conf.high = conf.high * 100
    )

  p <- ggplot(dat, aes(x = t, y = estimate)) +
    geom_point() +
    geom_errorbar(aes(ymin = conf.low, ymax = conf.high),
      width = 0.1, color = "black"
    ) +
    theme_bw() +
    geom_vline(xintercept = 0, linetype = "dashed") +
    geom_hline(yintercept = 0, linetype = "dashed") +
    xlab("Periods to first treatment") +
    ylab("Effect (Percentage Points)")

  return(p)
}

# PLOT =========================================================================

p_btw <- plotting_events(twfe_event$btw, "green")
p_ltw <- plotting_events(twfe_event$ltw, "green")
p_kw <- plotting_events(twfe_event$kw, "green")
